<template>
	<el-dialog :title="dialogType + '备份'" :visible.sync="visible" width="560px" :close-on-click-modal="false">
		<el-form ref="form" :model="formData" :rules="formRules" label-width="80px" class="backup_form_wrapper">
			<el-form-item label="备份名称" prop="name">
				<el-input v-model="formData.name" placeholder="请输入备份名称"></el-input>
			</el-form-item>
			<el-form-item label="备份描述" prop="content">
				<el-input type="textarea" v-model="formData.content" placeholder="请输入备份描述"></el-input>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" :loading="btnLoading" @click="handleSubmitForm">{{ dialogType }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
import moment from 'moment';
import { backupDatabase, updateBackup } from '@/api/system/tbSysBackup';
export default {
	props: {
		value: Boolean,
		data: {
			type: Object,
			default () {
				return {};
			}
		}
	},
	data() {
		return {
			visible: this.value,
			formData: {},
			formRules: {
				name: [{ required: true, message: '请输入备份名称', trigger: 'blur' }]
			},
			btnLoading: false
		};
	},
	computed: {
		addOrEdit() {
			return Object.keys(this.data).length === 0;
		},
		dialogType() {
			return this.addOrEdit ? '新增' : '修改';
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if(!flag) return false;
			if(this.addOrEdit) {
				this.formData = { name: moment().format('YYYY-MM-DD_HH:mm:ss') };
			} else {
				this.formData = { ...this.data };
			}
		}
	},
	methods: {
		//提交备份
		handleSubmitForm() {
			this.$refs['form'].validate(async (valid) => {
				if(!valid) return false;
				this.addOrEdit ? await this.backupDatabaseRequest() : await this.updateBackupRequest();
			});
		},

		//备份请求
		async backupDatabaseRequest() {
			let params = { ...this.formData };
			let openLoading = this.$loading({
				text: '数据库备份中……',
				background: 'rgba(0, 0, 0, 0.8)'
			});
			let result = await backupDatabase(params).then((res) => res.data);
			if(result.code === '0') {
				this.visible = false;
				setTimeout(() => {
					openLoading.close();
					this.$emit('refresh');
					this.$showCustomMessage('success', '添加备份成功');
				}, 5000)
			} else {
				openLoading.close();
			}
		},

		//更新备份信息请求
		async updateBackupRequest() {
			let params = { ...this.formData };
			let result = await updateBackup(params).then((res) => res.data);
			if(result.code === '0') {
				this.$showCustomMessage('success', '更新备份成功');
				this.$emit('refresh');
				this.visible = false;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.backup_form_wrapper {
	width: 100%;
	padding: 10px 10px 0 0;
	box-sizing: border-box;
}
</style>